#!/usr/bin/env python
# -*- encoding: utf-8 -*-
import os
import pandas as pd
from sicut.service.AbsRequestCallCppAPI import AbsRequestCallCppAPI
from sicut.BizConstants import BizConstants


class RequestSiCostAPI(AbsRequestCallCppAPI):
    """
    这个sql的意义就是取出这个母卷的所有子卷的有用信息，现在出了点问题  要用接口去读
    相当于对那5个子卷号去循环，调用接口
    每次只有一行数据，然后循环完是五行，有用的就几列  别的留着也行  然后合并成一个df
    就是相当于代替了那个sql
    而且接口就是之前那个sicost的接口  接口名和传入的json一模一样
    然后读出来之后可以不用定位到具体行
    各级300多列
    也不用定位到列  直接就全取了  弄到df里

    sql = " select distinct " \
      " mat_no,pre_unit_code,prod_end_time,mat_act_width,mat_act_wt,complex_decide_code,in_mat_no_1 " \
      " from MMSI.TMMSI96 " \
      " where event_id='42' " \
      " and in_mat_no_1='%s'" % (w)

    NOTE 取子卷信息，并
    """

    FIXED_COLUMNS = ['MAT_NO', 'PRE_UNIT_CODE', 'PROD_END_TIME', 'MAT_ACT_WIDTH', 'MAT_ACT_WT',
                     'COMPLEX_DECIDE_CODE', 'IN_MAT_NO_1']

    __MAX_TIMES = 2

    __curr_times = 0

    table_source = None

    def __init__(self, p_mat_no=None, p_json_template_object=BizConstants.create_playload_sicost(), p_table_source='1'):
        """

        :param p_mat_no:
        :param p_json_template_object:
        :param p_table_source: 两个来源表， 1就是历史表，0就是当前表；0的都要最后写到1里面；所以保险一点就是1没查到  就去0里查一下 还没查到就诊查不到
        """
        super(RequestSiCostAPI, self).__init__(p_mat_no=p_mat_no, p_json_template_object=p_json_template_object)

        self.table_source = p_table_source
        # 现在我们这个接口传进去是这4个参数,第二个参数是1
        # 如果当1的时候没查到时，把1改成0再查一次
        self.payload['Tables'][0]['Rows'][0][1] = p_table_source

    def _on_before_request(self, p_payload=None, p_headers=None):
        """

        :return:
        """
        RequestSiCostAPI.__curr_times += 1

    def _on_request_fail(self, p_exception=None):
        """

        :param p_exception:
        :return:
        """
        self.logger.error('RequestSiCostAPI._on_request_fail---->>\n%s' % (str(p_exception)))
        return False, pd.DataFrame(data=[], columns=RequestSiCostAPI.FIXED_COLUMNS)

    def _on_parsing(self, p_payload=None, p_response_dict=None):
        """

        :param p_response_dict:
        :return:
        """
        self.logger.info('RequestSiCostAPI._on_parsing')

        column_names = list()
        columns = p_response_dict['Tables'][0]['Columns']
        for c in columns:
            column_names.append(c['Name'])
        rows = p_response_dict['Tables'][0]['Rows']

        success = len(rows) > 0

        df = pd.DataFrame(data=rows, columns=column_names)
        except_column = list(set(column_names).difference(set(RequestSiCostAPI.FIXED_COLUMNS)))
        df.drop(except_column, axis=1, inplace=True)

        if success:
            RequestSiCostAPI.__curr_times = 0
        else:
            if RequestSiCostAPI.__curr_times < RequestSiCostAPI.__MAX_TIMES:
                self.logger.info(
                    'RequestSiCostAPI-try-again-request_times=%d' % (RequestSiCostAPI.__curr_times))
                success, df = RequestSiCostAPI(p_mat_no=self.mat_no,
                                               p_json_template_object=self.json_template_object,
                                               p_table_source='0').request()
                self.logger.info(
                    f'mat_no={self.mat_no}, table_source={self.table_source}, success={success}, RequestSiCostAPI-try-again-request_times={RequestSiCostAPI.__curr_times}, max_times={RequestSiCostAPI.__MAX_TIMES}')
            else:
                RequestSiCostAPI.__curr_times = 0
            
        return success, df

    def _on_parse_fail(self, p_response=None, p_exception=None):
        """

        :param p_exception:
        :return:
        """
        self.logger.error('RequestSiCostAPI._on_parse_fail---->>\n%s' % (str(p_exception)))
        return False, pd.DataFrame(data=[], columns=RequestSiCostAPI.FIXED_COLUMNS)
